#include "Teleport.h"
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>


void initTeleport(Teleport * pTeleport){

	pTeleport->id = 0;
	pTeleport->terrain_out = 0;
	pTeleport->terrain_in = 0;
	pTeleport->terrain_out_x = 0;
	pTeleport->terrain_out_y = 0;
	pTeleport->terrain_in_x = 0;
	pTeleport->terrain_in_y = 0;

}


Teleport * fillTeleport(int * nb){

 		FILE * fTeleport;
		Teleport * pTeleport;
		int i,res;

		fTeleport = fopen("data/Database/Teleport.dat","r");
		if(fTeleport == NULL)
		fTeleport = fopen("../data/Database/Teleport.dat","r");
		assert(fTeleport!=NULL);

		fscanf(fTeleport,"#nb = %d\n",nb);

		pTeleport = (Teleport *) malloc((*nb)*sizeof(Teleport));

		fscanf(fTeleport,"id terrain_out out_x out_y terrain_in in_x in_y\n");

		for(i = 0;i<(*nb);i++){
		initTeleport(pTeleport+i);
		res = fscanf(fTeleport,"%d %d %d %d %d %d %d\n",&((pTeleport+i)->id),&((pTeleport+i)->terrain_out),
			&((pTeleport+i)->terrain_out_x),&((pTeleport+i)->terrain_out_y),
			&((pTeleport+i)->terrain_in),&((pTeleport+i)->terrain_in_x),
			&((pTeleport+i)->terrain_in_y));
		assert(res == 7);

		}

	fclose(fTeleport);

	return pTeleport;

}

void freeTeleport(Teleport * tabTeleport){

	free(tabTeleport);

	tabTeleport = NULL;

}


int getTeleportID(const Teleport * pTeleport){
	return pTeleport->id;
}

int getTeleportTerOut(const Teleport * pTeleport){
	return pTeleport->terrain_out;
}
int getTeleportTerOutX(const Teleport * pTeleport){
	return pTeleport->terrain_out_x;
}
int getTeleportTerOutY(const Teleport * pTeleport){
	return pTeleport->terrain_out_y;
}
int getTeleportTerIn(const Teleport * pTeleport){
	return pTeleport->terrain_in;
}
int getTeleportTerInX(const Teleport * pTeleport){
	return pTeleport->terrain_in_x;
}
int getTeleportTerInY(const Teleport * pTeleport){
	return pTeleport->terrain_in_y;
}

int isTeleport(const Teleport * pTeleport,int nb,int x,int y,int ter){

	int i;
	for(i=0;i<nb;i++){
	if(pTeleport[i].terrain_out == ter && pTeleport[i].terrain_out_x == x
		&& pTeleport[i].terrain_out_y == y) return 1;

	}

return 0;
}

void teleportTestRegression(){

	Teleport * tabTeleport;
	int nb_teleport;
	printf("****** TEST TELEPORT START ************ \n");

	tabTeleport = fillTeleport(&nb_teleport);

	if(isTeleport(tabTeleport,nb_teleport,getTeleportTerOutX(tabTeleport+1),getTeleportTerOutY(tabTeleport+1),getTeleportTerOut(tabTeleport+1))){
		printf("Module fonctionne correctement.....\n");
	}else{
		printf("Attention! Module erreur....\n");
	}

	freeTeleport(tabTeleport);
	printf("****** TEST TELEPORT END ************** \n");
}


